import pymysql


class MB:
    # 创建msql连接
    def __init__(self, database, host='localhost', user='root', password='root', charset='utf8',
                 cursor_type=pymysql.cursors.Cursor):  # 传参  cursor_type=pymysql.cursors.Cursor或
        # 者字典cursor_type=pymysql.cursors.DictCursor
        # 初始化连接对象
        # 设置私有成员__
        self.__conn = pymysql.connect(host=host, user=user, password=password, charset=charset,
                                      database=database)
        # 初始化游标对象 不设置就是元祖
        self.__coursor = self.__conn(cursor_type)

    def read(self, sql):
        try:
            # 执行sql语句
            rows = self.__coursor.execute(sql)
        except Exception as e:
            self.__conn.rollback()
            return 0
        else:
            self.__conn.commit()
        return rows
    def write(self, sql):
        try:
            # 执行sql语句
            rows = self.__cursor.execute(sql)
        except Exception as e:
            # 回滚
            self.__conn.rollback()
            return 0
        else:
            # 提交
            self.__conn.commit()
        return rows


    def __del__(self):
        self.__coursor.close()
        self.__conn.close()


# if __name__ == '__main__':
#     db = MB('advanced', cursor_type=pymysql.cursors.DictCursor)  # 返回字典游标
#     rows, data = db.read('select * from student')
#     print(data)
#     name = input('name;')
#     rows, data = db.read(f'select * from student where stu_name=%s', [name])
#     print(data)
if __name__ == '__main__':
    db = MB('advanced', cursor_type=pymysql.cursors.Cursor)
    # 读操作
    rows, data = db.read('select * from student')
    if rows:
        print(rows, data)

    # 写操作
    rows = db.write("INSERT INTO student(stu_no, stu_name) VALUES('itsrc-017', '周杰伦1')")

    if rows:
        print('写入成功')
